package cn.cnlee.app.base;


import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.tqzhang.stateview.stateview.BaseStateControl;

import cn.cnlee.app.config.Constants;
import cn.cnlee.arch.base.AbsViewModel;
import cn.cnlee.arch.base.BaseActivity;
import cn.cnlee.arch.event.LiveBus;
import cn.cnlee.arch.util.ClassUtil;
import cn.cnlee.arch.util.Logger;
import cn.cnlee.arch.view.stateview.ErrorState;
import cn.cnlee.arch.view.stateview.LoadingState;
import cn.cnlee.arch.view.stateview.StateConstants;

/**
 * Activity的抽象类（ViewModel、LiveData、生命周期等相关）
 */
public abstract class AbsLifecycleActivity<T extends AbsViewModel> extends BaseActivity {

    protected T mViewModel;//当前activity所持有的ViewModel
    protected boolean needReloadData = false;

    public AbsLifecycleActivity() {
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        mViewModel = VMProviders(this, (Class<T>) ClassUtil.getTypeInstance(this, 0));
        dataObserver();
        LiveBus.get().getChannel(Constants.LOGIN_ACTION_NOTIFY_KEY).observe(this, loginDTO -> {
            needReloadData = true;
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (needReloadData) {
            loginNext();
            needReloadData = false;
        }
    }

    /**
     * 登录成功后事件（可能需要重新请求）
     */
    protected void loginNext() {
        Logger.e("=====absActivity=====loginNext==========");
    }

    /**
     * 创建viewModel的方法
     *
     * @param activity   当前Owner
     * @param modelClass The class of the ViewModel
     * @param <T>        The type parameter for the ViewModel.
     * @return A ViewModel that is an instance of the given type
     */
    protected <T extends ViewModel> T VMProviders(BaseActivity activity, @NonNull Class modelClass) {
        return (T) new ViewModelProvider(activity, new ViewModelProvider.AndroidViewModelFactory(this.getApplication())).get(modelClass);
    }

    /**
     * Repository中数据观察者处理方法
     */
    protected void dataObserver() {
    }

    @Override
    protected void onStateRefresh() {
        showLoading();
    }

    /**
     * 设置stateView 错误状态视图
     *
     * @param stateView
     * @param tag
     */
    protected void showError(Class<? extends BaseStateControl> stateView, Object tag) {
        loadManager.showStateView(stateView, tag);
    }

    protected void showError(Class<? extends BaseStateControl> stateView) {
        showError(stateView, null);
    }

    /**
     * 设置stateView 成功状态视图
     */
    protected void showSuccess() {
        loadManager.showSuccess();
    }

    /**
     * 设置stateView 正在加载状态视图
     */
    protected void showLoading() {
        loadManager.showStateView(LoadingState.class);
    }


    /**
     * StateView视图状态监听
     */
    protected Observer observer = new Observer<String>() {
        @Override
        public void onChanged(@Nullable String state) {
            if (!TextUtils.isEmpty(state)) {
                if (StateConstants.ERROR_STATE.equals(state)) {
                    showError(ErrorState.class, "2");
                } else if (StateConstants.NET_WORK_STATE.equals(state)) {
                    showError(ErrorState.class, "1");
                } else if (StateConstants.NO_LOGIN_STATE.equals(state)) {
                    showError(ErrorState.class, "-1");
                } else if (StateConstants.LOADING_STATE.equals(state)) {
                    showLoading();
                } else if (StateConstants.SUCCESS_STATE.equals(state)) {
                    showSuccess();
                } else if (StateConstants.NOT_DATA_STATE.equals(state)) {
                    showError(ErrorState.class, "0");
                }
            }
        }
    };

}
